package com.zbxx.practice.designpattern.proxy.dynamicproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author 万仁杰
 * @date 2019/05/31
 */
public class CglibProxy implements MethodInterceptor {


    private Enhancer enhancer = new Enhancer();

    public Object getProxyClass(Class clazz){
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    /**
     *
     * 拦截所有方法
     * 产生子类 去代理实现  动态修改字节码
    *@author 万仁杰
    *@since 2019/5/31
    */
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib proxy start");
        Object returnVal = methodProxy.invokeSuper(obj,args);
        System.out.println("cglib proxy end");
        return returnVal;
    }
}
